package com.example.socket;

import com.example.socket.config.WebSocketConfig;
import com.example.socket.model.ServletModel;
import com.example.socket.websocket.WebSockerHandler;
import com.example.socket.websocket.WebSocketService;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname ServletStart
 * @Description TODO
 * @Date 2023/4/27 11:07
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class ServletStart {

    private Integer port=8080;

    private Map<String,Servlet> urlServletMap=new HashMap<>();

    private Map<String, WebSockerHandler> webSockerHandlerMap=new HashMap<>();

    public ServletStart(Integer port) {
        this.port = port;
    }


    public void start(){
        //初始化映射
        initServletMapping();
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("server start success port:"+port);
            while (true) {
                Socket socket=serverSocket.accept();
                InputStream inputStream=socket.getInputStream();
                ServletRequest request=new ServletRequest(inputStream);
                if(request.isWebSocket()){
                    WebSockerHandler webSockerHandler=webSockerHandlerMap.get(request.getPath());
                    WebSocketService webSocketServer=new WebSocketService(webSockerHandler,request,socket.getOutputStream());
                    Thread thread = new Thread(webSocketServer);
                    thread.start();
                }else {
                    ServletResponse response=new ServletResponse(socket.getOutputStream());
                    dispatch(request,response);
                    request.close();
                    socket.close();
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加 servlet
     * @param url
     * @param servlet
     */
    public void addUrlServlet(String url,Servlet servlet){
        urlServletMap.put(url,servlet);
    }

    public void addUrlServlet(Map<String,ServletModel> map){
        for(Map.Entry< String,ServletModel> entry : map.entrySet()){
            System.out.println(entry.getKey());
            urlServletMap.put(entry.getKey(),entry.getValue());
        }
    }

    public void addUrlWebSocket(String url,WebSockerHandler webSockerHandler){
        webSockerHandlerMap.put(url,webSockerHandler);
    }


    private void  initServletMapping(){
        for (ServletMapping mapping : ServletMappingConfig.servletMappingList) {
            urlServletMap.put(mapping.getUrl(),mapping.getServlet());
        }
        for(Map.Entry<String,WebSockerHandler> ws: WebSocketConfig.webSockerHandlerMap.entrySet()){
            webSockerHandlerMap.put(ws.getKey(),ws.getValue());
        }
    }


    private void dispatch(ServletRequest request,ServletResponse response){
        if(!urlServletMap.containsKey(request.getPath())){
            response.wirte("接口没有发现");
            return;
        }
        Servlet servlet=urlServletMap.get(request.getPath());
        try {
            servlet.service(request,response);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ServletStart(8085).start();
    }
}
